<?php


namespace app\util;


use think\facade\Request;

/**
 * 数据处理工具类
 * Class Format
 * @package app\utils
 */
class Format
{
    /**
     * 数组转树结构静态方法
     * @param $rows
     * @param string $rowKey
     * @param string $pidKey
     * @param int $pid
     * @param int $level
     * @return array
     */
    public static function list2tree($rows, string $rowKey = "id", string $pidKey = "pid", int $pid = 0, int $level = 1): array
    {
        $result = [];

        foreach ($rows as $row) {
            if ($row[$pidKey] === $pid) {
                $row["level"] = $level;
                $row["children"] = self::list2tree($rows, $rowKey, $pidKey, $row["id"], $level + 1);
                array_push($result, $row);
            }
        }

        return $result;
    }

    /**
     * 格式化上传路径
     * @param $path
     * @param bool $prependDomain
     * @param bool $port
     * @return string
     */
    public static function uploadPath($path, bool $prependDomain, bool $port = true): string
    {
        $prefix = $prependDomain ? Request::domain($port) : "/";
        $path = preg_replace("/\\\\/", $path);
        return $prefix . $path;
    }
}